package com.nfcprogram.wifi;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

public class WiFiConnectToThread extends Thread {

	private static final int MAX_COUNT = 10;

	private static final String WI_FI_CONNECT_TO_THREAD = "WiFiConnectToThread";
	
	private static final int PORT_TARGET = 4432;
	private final WiFiService wiFiService;
	private String ip;

	private boolean keepAlive;

	private boolean connected;

	public WiFiConnectToThread(WiFiService wiFiService, String ip) {
		super(WI_FI_CONNECT_TO_THREAD);
		this.wiFiService = wiFiService;
		this.setIp(ip);
		keepAlive = true;
		connected = false;
	}

	@Override
	public void run(){
		InetSocketAddress inetSocketAddress = new InetSocketAddress(getIp(), PORT_TARGET);
		int count = 1; 
		while(keepAlive && (!connected && count < MAX_COUNT)){
			Socket socket = new Socket();
			try {
				socket.connect(inetSocketAddress,5000);
				if (WiFiConstants.D)  Log.d(WI_FI_CONNECT_TO_THREAD, "! Tentativa de conexao  #" + count+  " bem sucedida. ip -> "+ inetSocketAddress.getHostName());
				wiFiService.clientConnected(socket);
				connected = true;
			} catch (IOException e) {
				if (WiFiConstants.D)  Log.e(WI_FI_CONNECT_TO_THREAD, "! Erro na tentativa #" + count+ " ao tentar conectar WiFi no ip ->  " + getIp());
				e.printStackTrace();
				try {
					Thread.sleep(2*1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			count++;
		}
		keepAlive = false;
	}
	
	public boolean hadConnected(){
		if(keepAlive)
			return true;
		else
			return connected;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getIp() {
		return ip;
	}
	
	public void cancel(){
		keepAlive = false;
		this.interrupt();
	}

	

}
